import request from "@/lib/request";
import type { AxiosRequestConfig } from "axios";

// 响应数据类型定义
export interface ApiResponse<T = any> {
  code: number;
  message: string;
  data: T;
  success: boolean;
}

// 文案内容类型
export interface TextContent {
  id: number;
  content: string;
  createTime: string;
  updateTime: string;
  userId: number;
  // 根据实际返回数据可能需要添加更多字段
}

// 生成的图片类型
export interface GeneratedImage {
  id: number;
  imageUrl: string;
  prompt: string;
  createTime: string;
  updateTime: string;
  userId: number;
  // 根据实际返回数据可能需要添加更多字段
}

// 查询用户图生文案历史记录参数类型
export interface GetTextHistoryParams {
  userId: number;
}

// 查询用户图扩展历史记录参数类型
export interface GetImageHistoryParams {
  userId: number;
}

/**
 * 操作日志服务类
 * 提供用户操作历史记录的查询功能
 */
export class LogService {
  /**
   * 查询用户图生文案历史记录
   * @param params 查询参数
   * @returns Promise<TextContent[]>
   */
  static async getTextHistory(
    params: GetTextHistoryParams
  ): Promise<TextContent[]> {
    const config: AxiosRequestConfig = {
      method: "GET",
      url: `/operation-log/user/${params.userId}/image-to-text`,
      headers: {
        "Content-Type": "application/json",
      },
    };
    return request<TextContent[]>(config);
  }

  /**
   * 查询用户图扩展历史记录
   * @param params 查询参数
   * @returns Promise<GeneratedImage[]>
   */
  static async getImageHistory(
    params: GetImageHistoryParams
  ): Promise<GeneratedImage[]> {
    const config: AxiosRequestConfig = {
      method: "GET",
      url: `/operation-log/user/${params.userId}/image-to-image`,
      headers: {
        "Content-Type": "application/json",
      },
    };
    return request<GeneratedImage[]>(config);
  }

  /**
   * 批量查询用户操作历史记录
   * @param userId 用户ID
   * @returns Promise<{ textHistory: TextContent[], imageHistory: GeneratedImage[] }>
   */
  static async getAllHistory(userId: number): Promise<{
    textHistory: TextContent[];
    imageHistory: GeneratedImage[];
  }> {
    try {
      const [textHistory, imageHistory] = await Promise.all([
        this.getTextHistory({ userId }),
        this.getImageHistory({ userId }),
      ]);
      return {
        textHistory,
        imageHistory,
      };
    } catch (error) {
      console.error("获取历史记录失败:", error);
      return {
        textHistory: [],
        imageHistory: [],
      };
    }
  }

  /**
   * 格式化时间显示
   * @param dateString 日期字符串
   * @returns 格式化后的时间字符串
   */
  static formatTime(dateString: string): string {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now.getTime() - date.getTime();

    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (minutes < 1) {
      return "刚刚";
    } else if (minutes < 60) {
      return `${minutes}分钟前`;
    } else if (hours < 24) {
      return `${hours}小时前`;
    } else if (days < 7) {
      return `${days}天前`;
    } else {
      return date.toLocaleDateString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
      });
    }
  }

  /**
   * 按时间排序历史记录
   * @param records 历史记录数组
   * @param order 'asc' | 'desc' 排序方式
   * @returns 排序后的数组
   */
  static sortByTime<T extends { createTime: string }>(
    records: T[],
    order: "asc" | "desc" = "desc"
  ): T[] {
    return [...records].sort((a, b) => {
      const timeA = new Date(a.createTime).getTime();
      const timeB = new Date(b.createTime).getTime();
      return order === "desc" ? timeB - timeA : timeA - timeB;
    });
  }

  /**
   * 过滤历史记录
   * @param records 历史记录数组
   * @param keyword 搜索关键词
   * @returns 过滤后的数组
   */
  static filterRecords<T extends { content?: string; prompt?: string }>(
    records: T[],
    keyword: string
  ): T[] {
    if (!keyword.trim()) return records;

    const lowerKeyword = keyword.toLowerCase();
    return records.filter(record => {
      if ("content" in record && record.content) {
        return record.content.toLowerCase().includes(lowerKeyword);
      }
      if ("prompt" in record && record.prompt) {
        return record.prompt.toLowerCase().includes(lowerKeyword);
      }
      return false;
    });
  }
}

// 类型已经在上面导出，这里不需要重复导出
